<template>
  <a-layout class="main-layout">
    <!-- 侧边栏 -->
    <a-layout-sider v-model:collapsed="collapsed" :trigger="null" collapsible :width="200" :collapsed-width="60" class="layout-sider">
      <!-- Logo区域 -->
      <div class="logo-container">
        <div class="logo">
          <div v-if="!collapsed" class="logo-icon">📜</div>
          <span v-if="!collapsed" class="logo-text">生死簿管理系统</span>
          <div v-else class="logo-icon-mini">📜</div>
        </div>
      </div>

      <!-- 导航菜单 -->
      <a-menu :key="menuKey" :selected-keys="selectedKeys" :open-keys="openKeys" mode="inline" theme="dark" class="sidebar-menu" @click="handleMenuClick">
        <a-menu-item key="/dashboard">
          <template #icon>
            <DashboardOutlined />
          </template>
          <span>工作台首页</span>
        </a-menu-item>

        <a-menu-item key="/archives">
          <template #icon>
            <UserOutlined />
          </template>
          <span>生灵档案管理</span>
        </a-menu-item>

        <a-menu-item key="/life-death">
          <template #icon>
            <ClockCircleOutlined />
          </template>
          <span>寿命与生死管理</span>
        </a-menu-item>

        <a-menu-item key="/karma">
          <template #icon>
            <TrophyOutlined />
          </template>
          <span>因果业力系统</span>
        </a-menu-item>

        <a-menu-item key="/reincarnation">
          <template #icon>
            <ReloadOutlined />
          </template>
          <span>轮回转世系统</span>
        </a-menu-item>

        <a-menu-item key="/judgment">
          <template #icon>
            <BankOutlined />
          </template>
          <span>地府审判系统</span>
        </a-menu-item>

        <a-menu-item key="/salvation">
          <template #icon>
            <HeartOutlined />
          </template>
          <span>超度与救赎</span>
        </a-menu-item>

        <a-menu-item key="/statistics">
          <template #icon>
            <BarChartOutlined />
          </template>
          <span>统计分析中心</span>
        </a-menu-item>

        <a-menu-item key="/management">
          <template #icon>
            <TeamOutlined />
          </template>
          <span>地府机构管理</span>
        </a-menu-item>

        <a-menu-item key="/files">
          <template #icon>
            <FolderOutlined />
          </template>
          <span>档案文件管理</span>
        </a-menu-item>
      </a-menu>
    </a-layout-sider>

    <!-- 主体内容区 -->
    <a-layout class="main-content-layout" :class="{ collapsed }">
      <!-- 顶部导航栏 -->
      <a-layout-header class="layout-header">
        <div class="header-left">
          <!-- 折叠按钮 -->
          <a-button type="text" :icon="collapseIcon" @click="toggleCollapsed" class="collapse-btn" />

          <!-- 面包屑导航 -->
          <a-breadcrumb class="breadcrumb">
            <a-breadcrumb-item v-for="item in breadcrumbItems" :key="item.path">
              <router-link v-if="item.path" :to="item.path">{{ item.title }}</router-link>
              <span v-else>{{ item.title }}</span>
            </a-breadcrumb-item>
          </a-breadcrumb>
        </div>

        <div class="header-right">
          <!-- 系统状态 -->
          <div class="system-status">
            <a-badge :count="systemInfo.pendingCases" :offset="[10, 0]">
              <BellOutlined class="status-icon" />
            </a-badge>
            <span class="status-text">在线: {{ systemInfo.onlineUsers }}人</span>
          </div>

          <!-- 用户信息 -->
          <a-dropdown>
            <a-space class="user-info">
              <a-avatar :src="userInfo.avatar" :size="32">
                {{ userInfo.name?.charAt(0) }}
              </a-avatar>
              <span class="user-name">{{ userInfo.name }}</span>
              <DownOutlined />
            </a-space>

            <template #overlay>
              <a-menu @click="handleUserMenuClick">
                <a-menu-item key="profile">
                  <UserOutlined />
                  个人信息
                </a-menu-item>
                <a-menu-item key="settings">
                  <SettingOutlined />
                  系统设置
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item key="logout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </a-layout-header>

      <!-- 主内容区 -->
      <a-layout-content class="layout-content">
        <div class="content-wrapper">
          <router-view />
        </div>
      </a-layout-content>

      <!-- 底部状态栏 -->
      <a-layout-footer class="layout-footer">
        <div class="footer-content">
          <span>生死簿管理系统 v{{ systemInfo.version }}</span>
          <span>当前时间: {{ currentTime }}</span>
          <span>今日审判: {{ systemInfo.todayJudgments }}件</span>
        </div>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, h, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  DashboardOutlined,
  UserOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  ReloadOutlined,
  BankOutlined,
  HeartOutlined,
  BarChartOutlined,
  TeamOutlined,
  FolderOutlined,
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  BellOutlined,
  DownOutlined,
  SettingOutlined,
  LogoutOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons-vue'
import { Modal } from 'ant-design-vue'
import { useAppStore, useUserStore } from '@/stores'

// 路由
const router = useRouter()
const route = useRoute()

// 状态管理
const appStore = useAppStore()
const userStore = useUserStore()

// 响应式数据
const selectedKeys = ref([])
const openKeys = ref([])
const currentTime = ref('')
const menuKey = ref(0) // 用于强制重新渲染菜单

// 计算属性
const collapsed = computed({
  get: () => appStore.collapsed,
  set: (value) => appStore.toggleCollapsed()
})

const userInfo = computed(() => userStore.userInfo)
const systemInfo = computed(() => appStore.systemInfo)

// 折叠按钮图标 - 使用计算属性避免在模板中使用h函数
const collapseIcon = computed(() => {
  return collapsed.value ? h(MenuUnfoldOutlined) : h(MenuFoldOutlined)
})

// 面包屑导航
const breadcrumbItems = computed(() => {
  const matched = route.matched.filter((item) => item.meta && item.meta.title)
  return matched.map((item) => ({
    title: item.meta.title,
    path: item.path
  }))
})

// 定时器ID
let timeInterval = null

// 方法
const toggleCollapsed = () => {
  appStore.toggleCollapsed()
}

const handleMenuClick = ({ key }) => {
  // 立即更新选中状态
  selectedKeys.value = [key]
  // 强制菜单重新渲染以确保选中状态显示
  menuKey.value++
  // 进行路由跳转
  router.push(key)
}

const handleUserMenuClick = ({ key }) => {
  switch (key) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

const handleLogout = () => {
  Modal.confirm({
    title: '确认退出',
    icon: h(ExclamationCircleOutlined),
    content: '您确定要退出生死簿管理系统吗？',
    okText: '确认退出',
    okType: 'danger',
    cancelText: '取消',
    centered: true,
    onOk() {
      userStore.logout()
      router.push('/login')
    },
    onCancel() {
      // 用户取消，无需执行任何操作
    }
  })
}

const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 更新选中的菜单项
const updateSelectedKeys = (path) => {
  // 路径映射表，按长度排序，确保更具体的路径优先匹配
  const pathMap = ['/dashboard', '/archives', '/life-death', '/karma', '/reincarnation', '/judgment', '/salvation', '/statistics', '/management', '/files']

  // 找到匹配的基础路径，优先匹配更具体的路径
  let basePath = '/'
  for (const menuPath of pathMap) {
    if (path.startsWith(menuPath)) {
      basePath = menuPath
      break
    }
  }

  // 只在选中状态不匹配时才更新，避免不必要的覆盖
  if (selectedKeys.value[0] !== basePath) {
    selectedKeys.value = [basePath]
  }
}

// 监听路由变化 - 使用watch而不是router.afterEach
watch(
  () => route.path,
  (newPath) => {
    updateSelectedKeys(newPath)
  },
  { immediate: true }
)

// 监听selectedKeys变化
watch(selectedKeys, (newKeys, oldKeys) => {}, { deep: true })

// 生命周期
onMounted(() => {
  // 初始化状态
  appStore.initAppState()
  userStore.initUserInfo()

  // 初始化选中的菜单项
  updateSelectedKeys(route.path)

  // 启动时间更新
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
})

onUnmounted(() => {
  if (timeInterval) {
    clearInterval(timeInterval)
  }
})
</script>

<style lang="scss" scoped>
.main-layout {
  min-height: 100vh;

  .layout-sider {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    z-index: 100;

    .logo-container {
      height: 64px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid $border-color;

      .logo {
        display: flex;
        align-items: center;
        gap: $spacing-sm;

        .logo-icon {
          font-size: 28px;
          line-height: 1;
        }

        .logo-icon-mini {
          font-size: 20px;
          line-height: 1;
        }

        .logo-text {
          color: $secondary-color;
          font-size: $font-size-md;
          font-weight: bold;
          white-space: nowrap;
          overflow: hidden;
        }
      }
    }

    .sidebar-menu {
      height: calc(100vh - 64px);
      border-right: none;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }

  .main-content-layout {
    margin-left: 200px;
    transition: margin-left $transition-normal;
    display: flex;
    flex-direction: column;
    min-height: 100vh;

    &.collapsed {
      margin-left: 60px;
    }
  }

  .layout-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 $spacing-lg;
    height: 64px;

    .header-left {
      display: flex;
      align-items: center;
      gap: $spacing-lg;

      .collapse-btn {
        color: $text-primary;
        font-size: $font-size-lg;

        &:hover {
          color: $primary-color;
        }
      }

      .breadcrumb {
        color: $text-secondary;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: $spacing-lg;

      .system-status {
        display: flex;
        align-items: center;
        gap: $spacing-md;

        .status-icon {
          color: $text-secondary;
          font-size: $font-size-lg;
          cursor: pointer;

          &:hover {
            color: $primary-color;
          }
        }

        .status-text {
          color: $text-secondary;
          font-size: $font-size-sm;
        }
      }

      .user-info {
        cursor: pointer;
        padding: $spacing-sm;
        border-radius: $border-radius-md;
        transition: background-color $transition-fast;

        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }

        .user-name {
          color: $text-primary;
          font-size: $font-size-md;
        }
      }
    }
  }

  .layout-content {
    margin: $spacing-lg;
    flex: 1;

    .content-wrapper {
      background: rgba(255, 255, 255, 0.02);
      border-radius: $border-radius-lg;
      padding: $spacing-lg;
      backdrop-filter: blur(10px);
    }
  }

  .layout-footer {
    height: 48px;
    padding: 0 $spacing-lg;
    border-top: 1px solid $border-color;

    .footer-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: $text-tertiary;
      font-size: $font-size-sm;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .main-layout {
    .layout-sider {
      position: fixed;
      z-index: 1000;
    }

    .main-content-layout {
      margin-left: 0;
    }
  }
}
</style>
